import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { cacheConf } from '@conf/cache.conf';
import { STColumn, STComponent, STChange, STData } from '@delon/abc/st';
import { SFUISchema, SFSchema, SFComponent, SFUploadWidgetSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { EACacheService, EAEnvironmentService } from '@shared';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { VehicleService } from '../../../services/vehicle.service';
import { apiConf } from '@conf/api.conf';
import { Observable, Observer } from 'rxjs';

// import { CarSettleCarauthComponent } from '../carauth/carauth.component';

@Component({
  selector: 'app-car-setmodal',
  templateUrl: './setmodal.component.html',
  styleUrls: ['./setmodal.component.less']
})
export class CarSettleSetmodalComponent implements OnInit, AfterViewInit {
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sf2', { static: false }) sf2!: SFComponent;
  _$expand = false;
  formData: any = {};
  ui!: SFUISchema;
  ui2!: SFUISchema;
  schema!: SFSchema;
  schema2!: SFSchema;
  columns!: STColumn[];
  tableData: any = [];
  companyData: any = {};
  i: any = {}
  flag = false
  constructor(
    private modal: NzModalRef,
    private eaCacheSrv: EACacheService,
    public service: VehicleService,
    private modalHelper: ModalHelper,
    private cdr: ChangeDetectorRef,
    private envSrv: EAEnvironmentService,

  ) { }

  /**
    * 查询字段个数
    */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    return { ...params };
  }

  /**
   * 选中行
   */
  get selectedRows() {
    return this.st?.list.filter((item: any) => item.checked) || [];
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }
  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.companyData = this.eaCacheSrv.get(cacheConf.env)
    this.initSF();
    this.initST()
    this.initSF2()
    this.initData()
  }

  ngAfterViewInit(): void {
    this.cdr.detectChanges();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        mobiles: { title: '手机号', maxLength: 11, type: 'string', ui: { showRequired: false, placeholder: '请输入手机号', } },
      },
    };
    this.ui = {
      '*': { spanLabelFixed: 90, grid: { span: 8, gutter: 8 } },
    };
  }
  // get selectedRows() {
  //   return this.st?.list.filter(item => item.checked) || [];
  // }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      { title: '司机姓名', index: 'userName', className: 'text-center' },
      { title: '司机手机号', index: 'telephone', className: 'text-center' },
      { title: '身份证号', index: 'projectId', className: 'text-center' },
      // {
      //   title: '车主申明/挂靠协议',
      //   width: '180px',
      //   className: 'text-center',
      //   buttons: [
      //     { text: '上传协议', click: (_record: any) => this.add(_record), iif: (item) => !item.bindStatus },
      //   ],
      // },
    ];
  }
  initData(flag?: any) {
    if (this.sf?.value.mobiles) {
      console.log(this.sf?.value.mobiles);
      
      this.service.request(`${this.service.$api_likeDriverUserByMobile}?mobiles=${this.sf?.value.mobiles}`).subscribe(res => {
        this.flag = flag
        if (res && res.length) {
          this.tableData = res;
          setTimeout(() => {
            this.st.reload()
          })
        } else {
          this.tableData = []
        }
      })
    }
  }
  /**
   * 数据列表状态变化事件
   */
  change(change: STChange) {
    // console.log(change);
  }

  /**
   * 新增
   */
  add(item: any) {
    const params: any = {
      appUserId: this.i.appUserId,
      carId: item.carId,
      bindType: 0
    }
    // this.service.request(this.service.$api_updateBindDriver, params).subscribe(res => {
    //   if (res) {
    //     this.service.msgSrv.success('添加成功');
    //     this.modal.close(true);
    //   }
    // })
  }
  addModal() {
    const i = {
      appUserId: this.i.appUserId,
      mobiles: this.sf?.value.mobiles,
      bindType: 0,
      flag: 'add'
    }
    // this.modalHelper.create(CarSettleCarauthComponent, { i }, { size: 'lg' }).subscribe((res) => {
    //   this.initData()
    // });
  }
  goBack() {
    window.history.go(-1);
  }
  close(): void {
    this.modal.close(true)
  }
  initSF2() {
    // 依据类型初始表单
    this.schema2 = {
      properties: {
        carProtocal: { title: '', type: 'string', ui: { hidden: true } },
        carProtocalWatermark: {
          type: 'string',
          title: '车主申明/挂靠协议',
          ui: {
            widget: 'upload',
            action: apiConf.waterFileUpload,
            fileType: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            change: (args: any) => {
              if (args.type === 'success') {
                this.sf2.setValue('/carProtocal', args.fileList[0].response.data.fullFilePath);
              }
            },
            beforeUpload: (file: any, fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt1M = file.size / 1024 / 1024 < 5;
                const fileType = 'image/png,image/jpeg';
                if (fileType.indexOf(file.type) === -1) {
                  this.service.msgSrv.warning('图片格式不正确！');
                  observer.complete();
                  return;
                }
                if (!isLt1M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt1M);
                observer.complete();
              });
            },
            multiple: false,
            listType: 'picture-card',
            showRequired: true,
          } as SFUploadWidgetSchema,
        },
      },
      required: ['carProtocal'],
    };
    this.ui2 = {
      '*': {
        spanLabelFixed: 200,
        grid: { span: 24 },
      },
    };
  }
  sure() {
    console.log(this.selectedRows);
    console.log(this.i);
    if (this.selectedRows.length <= 0) {
      this.service.msgSrv.error('未选择司机！');
      return;
    }
    if (this.selectedRows.length > 1) {
      this.service.msgSrv.error('只能选择一位司机！');
      return;
    }
    console.log(this.sf2.valid);
    console.log(this.sf2.value);
    
    if (!this.sf2.value.carProtocalWatermark) {
      this.service.msgSrv.error('未上传车主申明/挂靠协议！');
      return;
    }
    let list: any ='';
    let listName: any ='';
    this.selectedRows.forEach(item => {
      list = item.appUserId;
      listName = item.userName;
    });
    let params = {
      bindType: 1,
      driverBind: 1,
      carId: this.i?.carId || this.i?.id,
      appUserName:list,
      appUserId:list,
      carProtocal: this.sf2.value.carProtocal
    }
    this.service.request(this.service.$api_saveOperateDriverCar, params).subscribe((res:any) => {
      console.log(res);
      if(res) {
        this.service.msgSrv.success('添加成功！');
        this.modal.destroy(true)
      }
    })
  }
}
